package cn.xiaolang.thread.juc;

import cn.xiaolang.common.utils.Monitor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 基于线程池的invokeAll方法，异步调用多个子任务，并获取每个子任务的执行结果
 *
 * @author Dean
 * @date 2023/9/14
 */
@Slf4j
public class ThreadPoolInvokeAllStarted {

    public static void main(String[] args) throws InterruptedException {
        // 创建一个线程池,执行多个子任务
        ExecutorService service = Executors.newFixedThreadPool(3);
        List<Callable<Object>> tasks = new ArrayList<>();

        Monitor.begin();
        tasks.add(() -> {
            Thread.sleep(1000);
            return 1;
        });

        tasks.add(() -> {
            Thread.sleep(2000);
            return "A";
        });

        tasks.add(() -> {
            Thread.sleep(5000);
            return "B";
        });
        // 基于invokeAll异步调用所有子任务
        List<Future<Object>> futures = service.invokeAll(tasks);
        futures.forEach(temp -> {
            try {
                log.info("exec result:{}", temp.get());
            } catch (InterruptedException | ExecutionException e) {
                log.error("exec error:", e);
                Thread.currentThread().interrupt();
            }
        });
        futures.clear();
        Monitor.end("all task execute over:");
        service.shutdown();
    }

}
